<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true">
      <el-form-item label="年度">
        <el-date-picker v-model="queryParams.startTime" value-format="yyyy" type="year" placeholder="开始年度" @change="handleStartYearChange"></el-date-picker>
        <span style="margin: 0 10px">至</span>
        <el-date-picker v-model="queryParams.endTime" value-format="yyyy" type="year" placeholder="结束年度" :min-date="queryParams.startTime" @change="handleEndYearChange"></el-date-picker>
      </el-form-item>

      <el-form-item label="归档单位">
        <treeselect v-model="queryParams.deptId" :options="optionSelect" :show-count="true" placeholder="请选择归属部门" style="width:242px;" :normalizer="normalizer"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-s-data"  @click="count">统计</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download"  @click="exportExcel">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-printer"  @click="print">打印</el-button>
      </el-col>
    </el-row>

    <div style="width: 70%; margin: 0 auto;">
      <table class="custom-table">
        <thead>
        <tr class="title">
          <th :colspan="dynamicColumns.length + 4" style="border: 0 !important;">
            <h1 style="font-size: 28px;" class="h1">
              {{ title }}
            </h1>
          </th>
        </tr>
        <tr class="dates">
          <th :colspan="dynamicColumns.length + 4" style="border: 0 !important;">
            <h3 style="font-size: 20px;" class="h3">
              {{ dates }}
            </h3>
          </th>
        </tr>
        <tr>
          <th rowspan="2">序号</th>
          <th rowspan="2">部门</th>
          <th :colspan="dynamicColumns.length">数量</th>
          <th rowspan="2">合计</th>
          <th rowspan="2">备注</th>
        </tr>
        <tr>
          <th v-for="column in dynamicColumns" :key="column.prop">{{ column.label }}</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in tableData" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.GDCS }}</td>
          <td v-for="column in dynamicColumns" :key="column.prop">{{ item[column.prop] }}</td>
          <td>{{ item.SUM }}</td>
          <td>
            <input type="text" v-model="item.REMARK" />
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <div style="width: 70%; height: 300px; margin: 0 auto; margin-top: 3%">
      <div id="histogram" style="width: 90%; height:100%;"></div>
    </div>
  </div>
</template>

<script>
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {kucun} from "@/api/archive/statistics/inboundStatistics/inboundStatistics";
import jquery from '@/api/archive/statistics/annualReport/jquery-1.7.1.min'
import * as XLSX from 'xlsx';
import * as echarts from "echarts";
export default {
  name: "index",
  components: { Treeselect },
  props: ["jquery"],
  data() {
    return {
      queryParams: {
        startTime: undefined,
        endTime: undefined,
        deptId: undefined
      },
      optionSelect: [],
      time: "",
      date: "",
      // 统计表格数据
      tableData: [],
      dynamicColumns: [],
      REMARK: "",
      title: "",
      dates: "",
      options: []
    }
  },
  created() {
    this.deptTreeSelectPost()
    const now = new Date();
    const currentYear = now.getFullYear();
    this.time = currentYear

    const currentMonth = String(now.getMonth() + 1).padStart(2, '0');
    const currentDate = String(now.getDate()).padStart(2, '0');
    this.date = currentYear + "年" + currentMonth + "月" + currentDate + "日"
    this.getList()
    this.title = this.time + "档案入库情况统计表"
    this.dates = "制表日期：" + this.date
  },
  methods: {
     // 只能选择数据下面有children 的数据，没有children的时候禁用
     normalizer(node) {
            if (node.children == null || node.children == undefined || !node.children.length) {
                delete node.children;
            }
            return node
        },
    //部门（单选）
    deptTreeSelectPost() {
      deptTreeSelect().then(response => {
        this.optionSelect = response.data;
      })
    },
    handleStartYearChange() {
      if(this.queryParams.endTime==null){
       
       this.queryParams.endTime=undefined;
     }

      if(this.queryParams.endTime < this.queryParams.startTime) {
        this.queryParams.startTime = this.queryParams.endTime;
      }
    },
    handleEndYearChange() {
      if(this.queryParams.endTime < this.queryParams.startTime) {
        this.queryParams.endTime = this.queryParams.startTime;
      }
      if (!this.queryParams.startTime) {
        this.queryParams.startTime = this.queryParams.endTime;
      }
    },
    count() {
      if(this.queryParams.startTime != undefined && this.queryParams.startTime != null){
        if(this.queryParams.endTime != undefined && this.queryParams.endTime != null) {
          this.time = this.queryParams.startTime + "~" + this.queryParams.endTime
        } else {
          this.time = this.queryParams.startTime + "~至今"
        }
      } else {
        const now = new Date();
        const currentYear = now.getFullYear();
        this.time = currentYear
      }
      this.getList()
    },
    // 获取列表数据
    getList() {
      this.title = this.time + "档案入库情况统计表"
      this.dates = "制表日期：" + this.date
      kucun(this.queryParams).then(response=>{
        this.dynamicColumns = response.data.dictData.map(item => {
          return {
            label: item.dictLabel,
            prop: item.dictValue
          }
        })
        this.tableData = response.data.data
        this.getHistogram()
      })
    },
    // 导出
    exportExcel() {
      const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table'));
      const workbook = XLSX.utils.book_new();
      // 将输入框的值作为备注添加到工作表中
      for (let i = 0; i < this.tableData.length; i++) {
        console.log("999999")
        const item = this.tableData[i];
        const columnLetter = XLSX.utils.encode_col(this.dynamicColumns.length + 3); // 获取动态列索引对应的字母表示形式
        console.log(columnLetter,"lhr-----------------------------------01")
        const cellAddress = `${columnLetter}${i + 5}`; // 组合动态列索引和行索引
        worksheet[cellAddress] = { v: item.REMARK };
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      console.log(worksheet)
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveAsExcel(excelBuffer, `入库统计_${new Date().getTime()}`);
    },

    saveAsExcel(buffer, filename) {
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${filename}.xlsx`;
      link.click();
    },
    // 打印
    print() {
      $("input").each(function () {
        $(this).attr('value', $(this).val());
      });

      const tableElement = document.querySelector('.custom-table');
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      const iframeDoc = iframe.contentWindow.document;

      iframeDoc.open();
      iframeDoc.write(`
          <html>
          <head>
<!--            <title>打印表单</title>-->
            <style>
              @media print {
                .h1 {
                  font-size: 28px;
                  text-align: center;
                }

                .h3 {
                  font-size: 20px;
                  text-align: right;
                }

                .table {
                  margin-top: 5px;
                  padding: 1%;
                }
                .custom-table {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table th,
                .custom-table td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .title {
                  heigth: 5em;
                  line-height: 5em;
                  text-align: center;
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:center;
                  letter-spacing:4px;
                  font-weight:bold;
                  font-family:宋体;
                  font-size:24px;
                  opacity:1;
                  margin: 0 auto;
                  background:rgba(255, 255, 255, 0) !important;
                  border: 0 !important;
                  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
                }

                .dates {
                  text-align: right;
                }

                input{
                    background:rgba(255, 255, 255, 0) !important;
                    border: 0 !important;
                    box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
                }
              }
            </style>
          </head>
          <body>
             ${tableElement.outerHTML}
            <script>
              window.onload = function() {
                window.print();
                window.close();
              }
            <\/script>
          </body>
          </html>
      `);
      iframeDoc.close();
    },

    // 制作柱状图
    getHistogram() {
      var GDCS = ['product']
      for (let i = 0; i < this.dynamicColumns.length; i++) {
        GDCS.push(this.dynamicColumns[i].label)
      }
      var data = this.tableData.map(item => {
        const newObj = {};
        newObj['product'] = item['GDCS'];
        this.dynamicColumns.forEach(obj => {
          const key = obj.label;
          const prop = obj.prop;
          newObj[key] = item[prop];
        });
        return newObj;
      });
      this.$nextTick(() => {
        var myChart = echarts.init(document.getElementById('histogram'));
        // 指定图表的配置项和数据
        var option = {
          legend: {},
          tooltip: {
          },
          dataset: {
            dimensions: GDCS,
            source: data,
          },
          grid: {
            containLabel: true,
            top: 50,
            x: 45,
            x2: 30,
            y2: 0
          },
          xAxis: {
            type: 'category',
            boundaryGap: true,
            axisLabel: {
              interval: 0,//横轴信息全部显示
              rotate: -15,//-15度角倾斜显示
            },
          },
          yAxis: {},
          series: [],
          color: ['#80b3ff', '#ffb366', '#6666ff', '#ff6600', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
        };
        for (var i = 0; i < this.dynamicColumns.length; i++) {
          option.series.push({ type: 'bar', barWidth: 20 });
        }
        // 使用配置绘制柱状图
        myChart.setOption(option);
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.h1 {
  font-size: 28px;
  text-align: center;
}

.h3 {
  font-size: 20px;
  text-align: right;
}

.table {
  margin-top: 5px;
  padding: 1%;
}
.custom-table {
  width: 100%; /* 设置表格宽度为100% */
  margin: 0 auto;
  border-collapse: collapse; /* 合并单元格边框 */
}

.custom-table th,
.custom-table td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.title {
  heigth: 5em;
  line-height: 5em;
  text-align: center;
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:center;
  letter-spacing:4px;
  font-weight:bold;
  font-family:宋体;
  font-size:24px;
  opacity:1;
  margin: 0 auto;
  background:rgba(255, 255, 255, 0) !important;
  border: 0 !important;
  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
}

.dates {
  text-align: right;
}
</style>
